package com.ggs.rg.ybjb.systemmodule.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ggs.rg.ybjb.pojomodule.pojo.TUser;
import com.ggs.rg.ybjb.systemmodule.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * ClassName:UserRealm
 * Package:com.ggs.rg.config
 * Description:
 *
 * @Date:2021/7/30 20:45
 * @Author:cxw
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /*Authorization 授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了Authorization 授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**Authentication 认证 证明
     *
     * @param token 令牌，可以从里面获得登录用户信息
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
        System.out.println("执行类Authentication的登录认证");
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        String phone = userToken.getUsername();
        //根据用户名查询数据库是否有该用户
        QueryWrapper<TUser> queryWrapper = new QueryWrapper();
        queryWrapper = queryWrapper.select("password").eq("phone",phone);
        TUser dataUser = userService.getOne(queryWrapper);
        if (dataUser == null) {
            // 当没有用户的时候，抛出异常
            throw new UnknownAccountException();
        }
        //盐值
        ByteSource solt = ByteSource.Util.bytes(userToken.getUsername());

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                phone,//用户名
                dataUser.getPassword(),//要对比的密码(数据库拿到的密码)
                solt, //设置盐值
                getName() //本对象名
        );
        return authenticationInfo;
        /**
        返回一个SimpleAuthenticationInfo对象
         SimpleAuthenticationInfo  翻译为:简单认证信息对象
        第一个参数：用户名/用户对象
        第二个参数：数据库获取到的密码
        第三个参数：盐值(这个盐一般是username)
        第四个参数：获取这个Realm的信息
        原理:底层会通过String password = new String(userToken.getPassword());拿到前端传过来的密码，
        之后同我们传入的数据库密码dataUser进行比对操作
         **/

    }
}
